﻿using System;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace SlamCms.Web
{
	public class CookieManager : ICookieManager
	{
		private readonly HttpContextBase httpContext;
		private readonly string domain;

		public CookieManager(HttpContextBase httpContext)
			: this(httpContext, FormsAuthentication.CookieDomain)
		{
		}

		public CookieManager(HttpContextBase httpContext, string domain)
		{
			this.httpContext = httpContext;
			this.domain = domain;
		}

		public void Set(string name)
		{
			this.Set(name, "1");
		}

		public void Set(string name, string value, bool httpOnly = true, bool defaultDomain = false)
		{
			var httpCookie = new HttpCookie(name, value);
			if (!defaultDomain)
				httpCookie.Domain = domain;
			httpCookie.HttpOnly = httpOnly;
			this.httpContext.Response.AppendCookie(httpCookie);
		}

		public bool Contains(string name)
		{
			return this.httpContext.Request.Cookies[name] != null || this.httpContext.Response.Cookies.AllKeys.Any(x => x == name);
		}

		public void Toggle(string name)
		{
			if (this.Contains(name))
				this.Remove(name);
			else
				this.Set(name);
		}

		public string Get(string name)
		{
			var requestCookie = this.httpContext.Request.Cookies[name];
			if (requestCookie != null)
				return requestCookie.Value;

			if (this.httpContext.Response.Cookies.AllKeys.Any(x => x == name))
				return this.httpContext.Response.Cookies[name].Value;

			return null;
		}

		public void Remove(string name, bool httpOnly = true, bool defaultDomain = false)
		{
			var httpCookie = new HttpCookie(name, string.Empty);
			if (!defaultDomain)
				httpCookie.Domain = domain;
			httpCookie.HttpOnly = httpOnly;
			httpCookie.Expires = DateTime.Now.AddDays(-1);
			this.httpContext.Response.AppendCookie(httpCookie);
		}
	}
}
